package com.ruoyi.campus.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.campus.domain.MonitorDevice;
import com.ruoyi.campus.service.IMonitorDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 监控设备Controller
 * 
 * @author ruoyi
 * @date 2024-01-17
 */
@RestController
@RequestMapping("/campus/device")
public class MonitorDeviceController extends BaseController
{
    @Autowired
    private IMonitorDeviceService monitorDeviceService;

    /**
     * 查询监控设备列表
     */
    @PreAuthorize("@ss.hasPermi('campus:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(MonitorDevice monitorDevice)
    {
        startPage();
        List<MonitorDevice> list = monitorDeviceService.selectMonitorDeviceList(monitorDevice);
        return getDataTable(list);
    }

    /**
     * 导出监控设备列表
     */
    @PreAuthorize("@ss.hasPermi('campus:device:export')")
    @Log(title = "监控设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MonitorDevice monitorDevice)
    {
        List<MonitorDevice> list = monitorDeviceService.selectMonitorDeviceList(monitorDevice);
        ExcelUtil<MonitorDevice> util = new ExcelUtil<MonitorDevice>(MonitorDevice.class);
        util.exportExcel(response, list, "监控设备数据");
    }

    /**
     * 获取监控设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('campus:device:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId)
    {
        return success(monitorDeviceService.selectMonitorDeviceByDeviceId(deviceId));
    }

    /**
     * 获取监控设备详细信息（包含关联信息）
     */
    @PreAuthorize("@ss.hasPermi('campus:device:query')")
    @GetMapping(value = "/detail/{deviceId}")
    public AjaxResult getDetail(@PathVariable("deviceId") Long deviceId)
    {
        return success(monitorDeviceService.selectMonitorDeviceDetail(deviceId));
    }

    /**
     * 根据设备编码查询设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:query')")
    @GetMapping("/code")
    public AjaxResult getByCode(@RequestParam String deviceCode)
    {
        return success(monitorDeviceService.selectMonitorDeviceByCode(deviceCode));
    }

    /**
     * 查询学校的设备列表
     */
    @PreAuthorize("@ss.hasPermi('campus:device:list')")
    @GetMapping("/school")
    public AjaxResult getBySchool(@RequestParam(required = false) Long schoolId, 
                                 @RequestParam(required = false) Integer deviceType)
    {
        List<MonitorDevice> list = monitorDeviceService.selectDevicesBySchool(schoolId, deviceType);
        return success(list);
    }

    /**
     * 查询在线设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:list')")
    @GetMapping("/online")
    public AjaxResult getOnlineDevices(@RequestParam(required = false) Long schoolId)
    {
        List<MonitorDevice> list = monitorDeviceService.selectOnlineDevices(schoolId);
        return success(list);
    }

    /**
     * 查询离线设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:list')")
    @GetMapping("/offline")
    public AjaxResult getOfflineDevices(@RequestParam(required = false) Long schoolId)
    {
        List<MonitorDevice> list = monitorDeviceService.selectOfflineDevices(schoolId, 30); // 默认30分钟离线
        return success(list);
    }

    /**
     * 查询故障设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:list')")
    @GetMapping("/fault")
    public AjaxResult getFaultDevices(@RequestParam(required = false) Long schoolId)
    {
        List<MonitorDevice> list = monitorDeviceService.selectFaultDevices(schoolId);
        return success(list);
    }

    /**
     * 查询维护设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:list')")
    @GetMapping("/maintenance")
    public AjaxResult getMaintenanceDevices(@RequestParam(required = false) Long schoolId)
    {
        List<MonitorDevice> list = monitorDeviceService.selectMaintenanceDevices(schoolId, 30); // 默认30天维护
        return success(list);
    }

    /**
     * 根据位置查询设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:list')")
    @GetMapping("/location")
    public AjaxResult getByLocation(@RequestParam Double latitude, 
                                   @RequestParam Double longitude, 
                                   @RequestParam Double distance,
                                   @RequestParam(required = false) Integer deviceType)
    {
        List<MonitorDevice> list = monitorDeviceService.selectDevicesByLocation(latitude, longitude, distance, deviceType);
        return success(list);
    }

    /**
     * 查询设备状态统计
     */
    @PreAuthorize("@ss.hasPermi('campus:device:statistics')")
    @GetMapping("/statistics/status")
    public AjaxResult getStatusStatistics(@RequestParam(required = false) Long schoolId)
    {
        Map<String, Object> statistics = monitorDeviceService.selectDeviceStatusStatistics(schoolId);
        return success(statistics);
    }

    /**
     * 查询设备类型统计
     */
    @PreAuthorize("@ss.hasPermi('campus:device:statistics')")
    @GetMapping("/statistics/type")
    public AjaxResult getTypeStatistics(@RequestParam(required = false) Long schoolId)
    {
        List<Map<String, Object>> statistics = monitorDeviceService.selectDeviceTypeStatistics(schoolId);
        return success(statistics);
    }

    /**
     * 查询设备心跳状态
     */
    @PreAuthorize("@ss.hasPermi('campus:device:heartbeat')")
    @GetMapping("/heartbeat")
    public AjaxResult getHeartbeatStatus(@RequestParam(required = false) Long schoolId)
    {
        List<Map<String, Object>> status = monitorDeviceService.selectDeviceHeartbeatStatus(schoolId);
        return success(status);
    }

    /**
     * 新增监控设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:add')")
    @Log(title = "监控设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MonitorDevice monitorDevice)
    {
        return toAjax(monitorDeviceService.insertMonitorDevice(monitorDevice));
    }

    /**
     * 修改监控设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:edit')")
    @Log(title = "监控设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MonitorDevice monitorDevice)
    {
        return toAjax(monitorDeviceService.updateMonitorDevice(monitorDevice));
    }

    /**
     * 删除监控设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:remove')")
    @Log(title = "监控设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds)
    {
        return toAjax(monitorDeviceService.deleteMonitorDeviceByDeviceIds(deviceIds));
    }

    /**
     * 更新设备心跳
     */
    @PreAuthorize("@ss.hasPermi('campus:device:heartbeat')")
    @PutMapping("/heartbeat")
    public AjaxResult updateHeartbeat(@RequestParam Long deviceId)
    {
        return toAjax(monitorDeviceService.updateDeviceHeartbeat(deviceId));
    }

    /**
     * 批量更新设备状态
     */
    @PreAuthorize("@ss.hasPermi('campus:device:edit')")
    @PutMapping("/updateStatusBatch")
    public AjaxResult updateStatusBatch(@RequestParam String deviceIds, @RequestParam Integer status)
    {
        String[] ids = deviceIds.split(",");
        Long[] deviceIdArray = new Long[ids.length];
        for (int i = 0; i < ids.length; i++) {
            deviceIdArray[i] = Long.parseLong(ids[i]);
        }
        return toAjax(monitorDeviceService.updateDeviceStatusBatch(deviceIdArray, status));
    }

    /**
     * 批量更新设备在线状态
     */
    @PreAuthorize("@ss.hasPermi('campus:device:edit')")
    @PutMapping("/updateOnlineStatusBatch")
    public AjaxResult updateOnlineStatusBatch(@RequestParam String deviceIds, @RequestParam Integer onlineStatus)
    {
        String[] ids = deviceIds.split(",");
        String[] deviceIdArray = new String[ids.length];
        System.arraycopy(ids, 0, deviceIdArray, 0, ids.length);
        return toAjax(monitorDeviceService.updateDeviceOnlineStatusBatch(deviceIdArray, onlineStatus));
    }

    /**
     * 更新离线设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:edit')")
    @PutMapping("/updateOffline")
    public AjaxResult updateOfflineDevices(@RequestParam Integer timeoutMinutes)
    {
        return toAjax(monitorDeviceService.updateOfflineDevices(timeoutMinutes));
    }

    /**
     * 校验设备编码
     */
    @PostMapping("/checkDeviceCodeUnique")
    public AjaxResult checkDeviceCodeUnique(@RequestBody MonitorDevice monitorDevice)
    {
        return success(monitorDeviceService.checkDeviceCodeUnique(monitorDevice));
    }

    /**
     * 校验IP端口
     */
    @PostMapping("/checkIpPortUnique")
    public AjaxResult checkIpPortUnique(@RequestBody MonitorDevice monitorDevice)
    {
        return success(monitorDeviceService.checkIpPortUnique(monitorDevice));
    }

    /**
     * 重启设备
     */
    @PreAuthorize("@ss.hasPermi('campus:device:edit')")
    @PostMapping("/reboot")
    public AjaxResult rebootDevice(@RequestParam Long deviceId)
    {
        // TODO: 实现设备重启逻辑
        return success("设备重启命令已发送");
    }

    /**
     * 设备截图
     */
    @PreAuthorize("@ss.hasPermi('campus:device:snapshot')")
    @PostMapping("/snapshot")
    public AjaxResult captureSnapshot(@RequestParam Long deviceId)
    {
        // TODO: 实现设备截图逻辑
        return success("设备截图命令已发送");
    }
} 